package utils

import cn.socialcredits.activity.setting.Settings
import com.typesafe.scalalogging.StrictLogging
import play.api.libs.json.Json
import play.api.mvc.{RequestHeader, Results}
import play.api.{Application, GlobalSettings}

import scala.concurrent.Future

/**
 * 全局配置
 * Created by jingyang on 15/7/17.
 */
object Global extends GlobalSettings with StrictLogging {

  override def onStart(app: Application) = {
    import cn.socialcredits.activity.data.implicits.JSONImplicits._
    logger.info("Global.onStarting:")
    logger.info(Json.stringify(Json.toJson(Settings.email)))
    logger.info(Json.stringify(Json.toJson(Settings.mongo)))
  }

  override def onStop(app: Application) = {
    logger.info("Global.onStopped:")
  }

  override def onError(request: RequestHeader, ex: Throwable) = {
    request.path match {
      case s if s.startsWith("/inapi/") =>
        logger.error(ex.toString, ex)
        Future.successful {
          Results.Ok(Json.obj("code" -> -1, "message" -> ex.getLocalizedMessage))
        }

      case _ =>
        super.onError(request, ex)
    }
  }

  //  override def onBadRequest(request: RequestHeader, error: String) = super.onBadRequest(request, error)
  //
  override def onRequestReceived(request: RequestHeader) = {
    if (!request.path.startsWith("/assets/")) {
      logger.debug("onRequestReceived: " + request)
    }
    super.onRequestReceived(request)
  }

  //
  //  override def onRouteRequest(request: RequestHeader) = {
  //    // TODO save visit history
  //
  //    super.onRouteRequest(request)
  //  }
}
